<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 工具栏 -->
      <page-tools>
        <template #left>
          <span>总记录数:{{ total }}条</span>
        </template>
        <template #right>
          <el-button size="small" type="warning" @click="$router.push('/import')">
            excel导入
          </el-button>
          <el-button size="small" type="danger" @click="exportData">excel导出</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">
            新增员工
          </el-button>
        </template>
      </page-tools>
      <!-- /工具栏 -->

      <!-- 表格 -->
      <el-card v-loading="loading" class="table-card">
        <el-table :data="employeeList" style="width: 100%" :border="true">
          <el-table-column
            align="center"
            label="序号"
            width="50"
            type="index"
            :index="indexMethod"
          >
          </el-table-column>
          <el-table-column align="center" prop="username" label="姓名" sortable>
          </el-table-column>
          <el-table-column align="center" label="头像" width="100">
            <template slot-scope="{ row }">
              <el-image
                style="width: 70px; height: 70px; border-radius:50%;"
                :src="row.staffPhoto"
                @click="handelShowCodeDialog(row.staffPhoto)"
              >
                <div slot="error" class="image-slot">
                  <img src="@/assets/common/leimu.jpg" alt="" />
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="workNumber" label="工号" sortable>
          </el-table-column>
          <el-table-column
            align="center"
            prop="formOfEmployment"
            label="聘用形式"
            sortable
            :formatter="formatEmployment"
          >
          </el-table-column>
          <el-table-column align="center" prop="departmentName" label="部门" sortable>
          </el-table-column>
          <el-table-column align="center" label="入职时间" sortable>
            <template slot-scope="{ row }">
              <div>{{ row.timeOfEntry | formatDate }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="enableState" label="账户状态" sortable>
            <template slot-scope="{ row }">
              <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="280" sortable fixed="right">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >
                查看
              </el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">
                角色
              </el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pagesize"
          :page-sizes="[2, 5, 15, 20]"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        >
        </el-pagination>
        <!-- /分页 -->
      </el-card>
      <!-- /表格 -->

      <!-- 新增员工的弹出层 -->
      <add-employee
        :showDialog.sync="showDialog"
        @closeDialog="closeDialog"
        @addEmployee="loadEmployeeList"
      ></add-employee>
      <!-- /新增员工的弹出层 -->

      <!-- 二维码的弹出层 -->
      <el-dialog
        title="二维码"
        :visible.sync="showCodeDialog"
        width="250px"
        class="codeDialog"
      >
        <canvas ref="myCanvas" class="myCanvas" />
      </el-dialog>
      <!-- /二维码的弹出层 -->

      <!-- 角色分配弹框组件 -->
      <assign-role
        :userId="userId"
        :showAssignDialog.sync="showAssignDialog"
        @closeAssignDialog="showAssignDialog = false"
      ></assign-role>
      <!-- /角色分配弹框组件 -->
    </div>
  </div>
</template>

<script>
import { reqGetEmployeeList, reqDelEmployeeById } from '@/api/employees'
import employees from '@/api/constant/employees'
import AddEmployee from './component/add-employee'
import QrCode from 'qrcode' // 二维码插件
import { formatDate } from '@/filters'
import EmployeeEnum from '@/api/constant/employees'
import AssignRole from './component/assign-role'

export default {
  name: 'Employees',
  components: { AddEmployee, AssignRole },
  data() {
    return {
      employeeList: [{ name: '蕾姆' }],
      page: 1, // 页码
      pagesize: 2, // 每页条数
      total: 10, // 总条数
      loading: false,
      showDialog: false, // 控制新增员工弹出层
      showCodeDialog: false, // 控制二维码弹出层
      userId: null,
      showAssignDialog: false, // 控制分配角色弹出层
      roleTotal: 10,
    }
  },
  created() {
    // 加载员工列表
    this.loadEmployeeList()
  },
  methods: {
    // 一、表格索引方法
    indexMethod(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    // 二、页码改变时触发的函数
    handleCurrentChange(page) {
      // console.log(page)
      this.page = page
      this.loadEmployeeList()
    },

    // 三、每页数量发生改变时触发的函数
    handleSizeChange(pagesize) {
      this.pagesize = pagesize
      this.loadEmployeeList()
    },

    // 四、获取员工列表
    async loadEmployeeList() {
      this.loading = true
      const data = await reqGetEmployeeList(this.page, this.pagesize)
      // console.log(data)
      this.$message.success('获取员工列表成功')
      this.employeeList = data.rows
      this.total = data.total
      this.loading = false
    },

    // 五、格式化聘用形式的方法
    formatEmployment(row, column, cellValue, index) {
      const obj = employees.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },

    // 六、删除员工
    async delEmployee(id) {
      try {
        // 1.提示用户是否执行删除操作
        await this.$confirm(
          '您确认要删除该员工的信息么? 注意: 该操作不可逆!',
          '温馨提示',
          { type: 'warning' }
        )
        try {
          // 2.确定删除发送请求
          await reqDelEmployeeById(id)
          // 3.当删除的是最后一页最后一条数据时,则请求上一页的内容
          if (this.employeeList.length === 1 && this.page > 1) {
            this.page--
          }
          this.$message.success('删除成功')
          this.loadEmployeeList()
        } catch {
          this.$message.error('删除失败')
        }
      } catch {
        // 取消删除操作
        this.$message.info('取消')
      }
    },

    // 七、关闭弹出层
    closeDialog(flag) {
      this.showDialog = flag
    },

    // 八、点击头像生成二维码
    handelShowCodeDialog(url) {
      // console.log(url)
      // 没有上传头像就不显示弹出层
      if (!url) return false
      this.showCodeDialog = true
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },

    // 九、导出excel表格
    exportData() {
      // 将来表头的信息
      const headers = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName',
      }

      // console.log('进行导出操作')
      import('@/vendor/Export2Excel').then(async excel => {
        // 这里注意: 要导出的是全部的数据, 就需要拿到全部的数据
        const data = await reqGetEmployeeList(1, this.total)
        // 整理数据, 整理出一个二维数组, 传给data, 进行导出渲染
        const resultArr = this.formatJSON(headers, data.rows)
        const multiHeader = [
          ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门'],
        ]
        // 合并
        // const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          // excel头部数据
          header: Object.keys(headers),
          data: resultArr, // 二维数组
          filename: '员工excel表', // 文件名
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx', // 生成的文件类型
          // multiHeader, // 复杂表头
          // merges, // 合并
        })
      })
    },

    // 十、根据表头信息headers的顺序, 以及全部的数据rows, 整理出一个二维数组, 返回
    formatJSON(headers, rows) {
      /*
        需要的结构
        [
          ['小王', 15751776629, 'xx-xx-xx', 正式, ... ],
          ['小李', 15751776630, 'xx-xx-xx', 非正式, ... ],
          ['小飞', 15751776631, 'xx-xx-xx', 未知, ... ]
        ]
      */
      const resultArr = rows.map(item => {
        const arr = []
        // 按照headers的顺序, 从item中取值, 存到arr中, 将来渲染
        Object.keys(headers).forEach(key => {
          // key => 姓名, headers[key] 才是username
          let value = item[headers[key]]
          // 判断, 如果是日期, 额外格式处理一下
          if (['timeOfEntry', 'correctionTime'].includes(headers[key]) && value) {
            // 是日期需要处理, 需要处理成 xxxx-xx-xx 的格式
            value = formatDate(value, 'YYYY-MM-DD')
          }
          if (headers[key] === 'formOfEmployment') {
            // 聘用形式也要处理, value 1, 2, ''
            const resObj = EmployeeEnum.hireType.find(obj => obj.id === value)
            // 如果没找到, resObj 就是 undefined
            value = resObj ? resObj.value : '暂未分配'
          }
          arr.push(value)
        })

        return arr
      })
      return resultArr
    },

    // 十一、点击角色按钮,给员工分配角色
    async editRole(id) {
      this.showAssignDialog = true
      this.userId = id
      // const data = await reqGetRoleList()
      // console.log(data)
      // this.roleTotal = data.total
    },
  },
}
</script>

<style lang="scss" scoped>
.table-card,
.el-pagination {
  margin-top: 20px;
}

img {
  width: 70px;
  height: 70px;
  border-radius: 50%;
}
.codeDialog {
  text-align: center;
}
.myCanvas {
  width: 164px !important;
  height: 164px !important;
}
</style>
